package com.speedata.blereaderdemo

import android.bluetooth.BluetoothDevice
import android.graphics.BitmapFactory
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.speedata.blereaderdemo.databinding.ActivityMainBinding
import nxp.smartproduct.manager.bluetooth.BleReaderViewModel

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var adapter: ArrayAdapter<String>
    private val deviceList = mutableListOf<BluetoothDevice>()
    private lateinit var viewModel: BleReaderViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        initView()
        initObserver()
    }

    fun initView() {
        adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1)
        binding.deviceListView.adapter = adapter

        // 列表点击连接
        binding.deviceListView.setOnItemClickListener { _, _, position, _ ->
            val device = deviceList[position]
            // 如果已连接同一个设备，提示并返回
            if (viewModel.bleManager.isConnected.value == true &&
                viewModel.bleManager.connectedDeviceAddress == device.address) {
                Toast.makeText(this, "已连接该设备", Toast.LENGTH_SHORT).show()
                return@setOnItemClickListener
            }
            viewModel.bleManager.connect(device) { success ->
                if (success) {
                    Toast.makeText(this, "连接成功", Toast.LENGTH_SHORT).show()
                    binding.logTextView.text = "蓝牙连接成功"
                    viewModel.bleManager.startBatteryPolling(5000)
                } else {
                    Toast.makeText(this, "连接失败", Toast.LENGTH_SHORT).show()
                }
            }
        }

        // 搜索按钮
        binding.scanButton.setOnClickListener {
            checkAndRequestPermissions()
        }

        binding.detectCardButton.setOnClickListener {
            requireBleConnected {
                viewModel.bleManager.scanCard()
            }
        }

        binding.getSnButton.setOnClickListener {
            requireBleConnected {
                viewModel.bleManager.transmit14443(cmd = byteArrayOf(0xAD.toByte(),0x30,0x20))
            }
        }

        binding.refreshScreenButton.setOnClickListener {
            requireBleConnected {
                val bitmap = BitmapFactory.decodeResource(resources, R.drawable.big_screen)
                viewModel.bleManager.startScreenUpdate(bitmap)
            }
        }

        binding.unlockButton.setOnClickListener {
            requireBleConnected {
                    viewModel.bleManager.startUnlock()
            }
        }

    }

    fun initObserver() {
        viewModel = ViewModelProvider(this)[BleReaderViewModel::class.java]

        // 监听扫描结果
        viewModel.bleManager.scanResults.observe(this) { devices ->
            deviceList.clear()
            deviceList.addAll(devices)
            adapter.clear()
            adapter.addAll(devices.map { "${it.name ?: "未知设备"}\n${it.address}" })
            adapter.notifyDataSetChanged()
        }

        // 监听电量
        viewModel.bleManager.batteryLevel.observe(this) { soc ->
            binding.voltageText.text = "当前电量: $soc %"
        }

        viewModel.bleManager.cardSnResult.observe(this) { result ->
            val (success, sn) = result
            if (success) {
                binding.logTextView.text = "寻卡成功: $sn\n"
            } else {
                binding.logTextView.text = "寻卡失败\n"
            }
        }

        viewModel.bleManager.transmitResult.observe(this) {result ->
            val (success, data) = result
            if (success) {
                val hexString = data
                binding.logTextView.text = "查询成功: ${Utils.hexToAscii(hexString!!)}\n"
            } else {
                binding.logTextView.text = "查询失败\n"
            }
        }
        viewModel.bleManager.unlockResult.observe(this) {result ->
            val (success, data) = result
            if (success) {
                binding.logTextView.text = "开锁成功：${data}"
            } else {
                binding.logTextView.text = "开锁失败：${data}"
            }
        }
        viewModel.bleManager.screenResult.observe(this) {result ->
            val (success, data) = result
            if (success) {
                binding.logTextView.text = "刷屏成功：${data}"
            } else {
                binding.logTextView.text = "刷屏失败：${data}"
            }
        }

    }

    // 权限检查与申请
    private fun checkAndRequestPermissions() {
        if (!BlePermissionHelper.hasAllPermissions(this)) {
            // 直接用 ActivityResultLauncher 申请
            requestPermissionsLauncher.launch(BlePermissionHelper.getRequiredPermissions())
        } else if (!BlePermissionHelper.isLocationEnabled(this)) {
            // 定位未开，提示并跳转设置
            Toast.makeText(this, "请先开启定位服务", Toast.LENGTH_SHORT).show()
            BlePermissionHelper.openLocationSettings(this)
        } else {
            viewModel.bleManager.stopBatteryPolling()
            viewModel.bleManager.stopScan()
            viewModel.bleManager.disconnect()
            startScan()
        }
    }

    private val requestPermissionsLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        if (permissions.all { it.value }) {
            startScan()
        } else {
            Toast.makeText(this, "请授予蓝牙和定位权限", Toast.LENGTH_SHORT).show()
        }
    }

    private fun startScan() {
        viewModel.bleManager.startScan()
        Toast.makeText(this, "开始扫描", Toast.LENGTH_SHORT).show()
    }


    private inline fun requireBleConnected(action: () -> Unit) {
        if (viewModel.bleManager.isConnected.value == true) {
            action()
        } else {
            Toast.makeText(this, "请先连接蓝牙设备", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        viewModel.bleManager.stopBatteryPolling()
        viewModel.bleManager.stopScan()
        viewModel.bleManager.disconnect()
    }
}